<template>
  <form class="w-50 m-auto mt-5">
    <div class="mb-3">
      <label for="field1" class="form-label">Пароль</label>
      <input type="text" :class="'form-control ' + get_msg_class('password')" id="field1" aria-describedby="emailHelp"
        v-model="password1" />
      <div class="invalid-feedback">
        {{ get_msg("password") }}
      </div>
    </div>
    <div class="mb-3">
      <label for="field2" class="form-label">Повторите пароль</label>
      <input type="password" :class="'form-control ' + get_msg_class('password')" v-model="password2" id="field2" />
      <div class="invalid-feedback">
        {{ get_msg("password") }}
      </div>
    </div>
    <button type="button" class="btn btn-primary" @click="sendForm">
      Установить новый пароль
    </button>
    <vue-basic-alert :duration="500" :closeIn="5000" ref="alert" />
  </form>
</template>
  
<script>
import VueBasicAlert from "vue-basic-alert";

export default {
  props: {
    tokens: Object,
    user: Object,
    code: String,
  },
  components: {
    VueBasicAlert
  },
  data() {
    return {
      password1: "",
      password2: "",
      detail: [],
    };
  },
  methods: {
    get_msg_class(name) {
      let ans = "";
      this.detail.forEach((el) => {
        if (el.loc[1] == name) {
          ans = "is-invalid";
        }
      });
      return ans;
    },
    get_msg(name) {
      let ans = "";
      this.detail.forEach((el) => {
        if (el.loc[1] == name) {
          ans = el.msg;
        }
      });
      return ans;
    },
    sendForm() {
      this.detail = [];
      if (this.password1 != this.password2) {
        this.detail = [
          {
            "type": "invalid_value",
            "loc": ["body", "password"],
            "msg": "Пароль должен совпадать"
          }
        ];
        return;
      }
      fetch(`${process.env.VUE_APP_BASE_URI}/recovery/${this.code}`, {
        method: "POST",
        headers: {
          Accept: "application/json",
          "Content-Type": "application/json",
        },
        body: JSON.stringify({
          password: this.password1,
        }),
      }).then(
        (resp) => {
          if (resp.status != 500) {
            resp.json().then(
              (body) => {
                if (resp.ok) {
                  // Редирект на страницу логина
                  this.$router.push("/login");
                } else if (resp.status == 422) {
                  this.detail = body.detail;
                } else {
                  this.$refs.alert.showAlert(
                    "error",
                    `${body.detail}`,
                    "Ошибка"
                  );
                }
              },
              () => {
                this.$refs.alert.showAlert(
                  "error",
                  "Ошибка сервера",
                  "Ошибка обработки json"
                );
              }
            );
          } else {
            this.$refs.alert.showAlert("error", "Ошибка сервера", "500 error");
          }
        },
        (err) => {
          this.$refs.alert.showAlert(
            "error",
            "Ошибка сервера",
            err.message
          );
        }
      );
    },
  },
};
</script>
  
<style></style>